package com.xiaowei.gym.gymjsp.ware.dao.impl;

import com.mysql.cj.util.StringUtils;
import com.xiaowei.gym.gymjsp.ware.dao.BaseDao;
import com.xiaowei.gym.gymjsp.ware.dao.UserDao;
import com.xiaowei.gym.gymjsp.ware.entity.UserEntity;
import com.xiaowei.gym.gymjsp.ware.util.JdbcUtil;
import com.xiaowei.gym.gymjsp.ware.util.PasswordEncryption;

import javax.swing.text.html.parser.Entity;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class USerDaoImpl implements UserDao {
    private static final PasswordEncryption ENCRYPTION = new PasswordEncryption();

    @Override
    public void createUser(UserEntity user) {
        try (Connection conn = JdbcUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(
                     "INSERT INTO users (username, password) VALUES (?, ?)")) {

            stmt.setString(1, user.getUsername());
            stmt.setString(2, PasswordEncryption.hash(user.getPassword()));

            stmt.executeUpdate();
        } catch (SQLException | NoSuchAlgorithmException throwables) {
            throwables.printStackTrace();
        }
    }

    @Override
    public int getUserCount() {
        int count = 0;
        String sql = "select count(1)  from gym_user";
       try {
           count = JdbcUtil.executeQuery(sql, rs -> {
               int counts = 0;
               if (rs.next()) {
                   counts = rs.getInt("count");
               }
               return counts;
           }, null);
       }catch (Exception exception){
           exception.printStackTrace();
       }
       return count;
    }

    @Override
    public UserEntity getUserById(int id) throws SQLException {
        UserEntity user = new UserEntity();
        try (Connection conn = JdbcUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(
                     "SELECT * FROM users WHERE id = ?")) {

            stmt.setInt(1, id);

            try (ResultSet rs = stmt.executeQuery()) {
                if (rs.next()) {
                    user.setId(rs.getInt("id"));
                    user.setUsername(rs.getString("username"));
                    user.setPassword(PasswordEncryption.decrypt(rs.getString("password")));
                    // 设置其他属性...
                    return user;
                } else {
                    return user;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return user;
    }

    @Override
    public UserEntity getUserByUsername(String username) throws SQLException {
        UserEntity user = new UserEntity();
        try (Connection conn = JdbcUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(
                     "SELECT * FROM users WHERE username = ?")) {
            stmt.setString(1, username);

            try (ResultSet rs = stmt.executeQuery()) {
                if (rs.next()) {
                    user.setId(rs.getInt("id"));
                    user.setUsername(rs.getString("username"));
                    user.setPassword(PasswordEncryption.decrypt(rs.getString("password")));
                    // 设置其他属性...
                    return user;
                } else {
                    return user;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return user;
    }

    @Override
    public boolean verifyPassword(UserEntity user, String password) throws NoSuchAlgorithmException {
        return PasswordEncryption.hash(password).equals(user.getPassword());
    }

    @Override
    public UserEntity validate(String username, String password) {
        String sql = "SELECT * FROM gym_user WHERE username = ? AND password = ?";
        UserEntity user = null;
            Object[] params={username,password};
            System.out.println("dao的params:"+params.toString());
            try {
                   user = JdbcUtil.executeQuery(sql, resultSet -> {
                       UserEntity userEntity = null;
                       if (resultSet.next()){
                           userEntity = new UserEntity();
                           userEntity.setId(resultSet.getInt("id"));
                           userEntity.setUsername(resultSet.getString("username"));
                           userEntity.setPassword(resultSet.getString("password"));
                           userEntity.setRole(resultSet.getInt("role"));
                       }
                    return userEntity;
                }, params);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        return user;
    }

    @Override
    public List<UserEntity> getUserList(String queryUserName, int currentPageNo, int pageSize) {
        List<UserEntity> userEntities = new ArrayList<>();
        StringBuilder sql = new StringBuilder();
        sql.append("select * from gym_admin");
        List<Object> list = new ArrayList<>();
        if (!StringUtils.isNullOrEmpty(queryUserName)){
            sql.append("where name like ?");
            list.add("%"+queryUserName+"%");
        }
        //在mysql数据库中，分页使用 limit startIndex，pageSize ; 总数
        sql.append(" order by creationDate DESC limit ?,?");
        currentPageNo = (currentPageNo - 1) * pageSize;
        list.add(currentPageNo);
        list.add(pageSize);
        Object[] params = list.toArray();
        System.out.println("sql ----> " + sql.toString());

        try {
            JdbcUtil.executeQuery(sql.toString(), rs -> {
                while (rs.next()){
                    UserEntity userEntity = new UserEntity();
                    userEntity.setUsername(rs.getString("name"));
                    userEntity.setId(rs.getInt("id"));
                    userEntity.setPassword(rs.getString("password"));
                    userEntity.setRole(rs.getInt("role"));
                    userEntities.add(userEntity);
                }
                return userEntities;
            },params);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return userEntities;
    }

}
